﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

/// <summary>
/// 操作Ini文件
/// IniFile ini = new IniFile(Application.StartupPath + "\\DeviceConfig.ini");
/// ini.WriteValue("Port", "PortName", Port.PortName); //写配置到ini
/// Port.PortName = ini.ReadValue("Port", "PortName", Port.PortName); //读配置ini内容
/// </summary>
namespace Hardware
{
    public class IniFile
    {

        public string path;

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section,
            string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section,
            string key, string def, StringBuilder retVal, int size, string filePath);

        public IniFile(string INIPath)
        {
            path = INIPath;
        }

        public void WriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this.path);
        }

        public string ReadValue(string Section, string Key, string Default)
        {
            StringBuilder buffer = new StringBuilder(255);
            GetPrivateProfileString(Section, Key, Default, buffer, 255, this.path);

            return buffer.ToString();
        }

        public void WriteValue(string Section, string Key, int Value)
        {
            WritePrivateProfileString(Section, Key, Value.ToString(), this.path);
        }

        public int ReadValue(string Section, string Key, int Default)
        {
            StringBuilder buffer = new StringBuilder(255);
            GetPrivateProfileString(Section, Key, Default.ToString(), buffer, 255, this.path);
            int result = 0;
            int.TryParse(buffer.ToString(), out result);
            return result;            
        }

        public bool ReadValue(string Section, string Key, bool Default)
        {
            try
            {
                StringBuilder buffer = new StringBuilder(255);
                GetPrivateProfileString(Section, Key, Default.ToString(), buffer, 255, this.path);
                int result = 0;
                int.TryParse(buffer.ToString(), out result); ;
                return Convert.ToBoolean(result);
            }
            catch (Exception)
            {
                return false;
            }
        }

        public double ReadDoubleValue(string Section, string Key, int Default)
        {
            StringBuilder buffer = new StringBuilder(255);
            GetPrivateProfileString(Section, Key, Default.ToString(), buffer, 255, this.path);
            double result = 0;
            double.TryParse(buffer.ToString(), out result);
            return result;
        }

    }
}
